<?php
namespace app\common\model;


class UserCartModel extends BaseModel
{
    protected $table = 'users_cart';



    public static function syncUserData($user_id,$session_id)
    {
        if(empty($user_id) || empty($session_id)){
            return ;
        }

        self::where(['session_id'=>$session_id])->select()->each(function($item)use($user_id){
            $where =[
                'uid'=>$user_id,
                'gid'=>$item['gid'],
            ];
            if(!empty($item['sku_id'])){
                $where['sku_id'] = $item['sku_id'];
            }
            $num = $item['num'];
            $model = self::where($where)->find();
            if(empty($model)){
               $model = new self();
               $model->setAttrs($where);
               $model->setAttr('num',0);
            }
            $model->setAttr('num',$model['num'] + $num);
            $model->save();
        });
        self::where(['session_id'=>$session_id])->delete();
    }

    /**
     * 获取用户购物车数量
     * @var $user_id int 用户id
     * @return integer
     * */
    public static function getNum($user_id,$session_id='')
    {
        if(empty($user_id) && empty($session_id)){
            return 0;
        }
        $where = [];
        $where[] = ['linkGoods.status','=',1];
        $where[] =['linkGoods.delete_time','=',null];
        if(!empty($user_id)){
            $where[] = ['user_cart_model.uid','=',$user_id];
        }else{
            $where[] = ['user_cart_model.session_id','=',$session_id];
        }
        return self::withJoin(['linkGoods'],'left')->where($where)->sum('num');
    }

    //添加购物车
    public static function cartAdd(UserModel $user_model=null,array $input_data = [])
    {
        $session_id = $input_data['session_id']??'';

        if(empty($input_data['goods_info']) || !is_array($input_data['goods_info'])) throw new \Exception('参数异常:goods_info');

        foreach ($input_data['goods_info'] as $vo){
            $goods_id = $vo['goods_id']??0;
            $sku_id = $vo['sku_id']??0;
            $num = $vo['num']??1;
//            $num = $num==-1?-1:1;
            //直接更改数量
            $change_num = $vo['c_num']??0;
            $change_num = $change_num<=0?1:$change_num;
            if(!$goods_id) continue;
            //查询产品信息
            $goods_model = GoodsModel::find($goods_id);
            if(empty($goods_model)) continue;
            $where = $data = ['gid'=>$goods_id,'sku_id'=>$sku_id];
            if ( empty($user_model) ){
                $where['session_id'] = $session_id;
                $data['session_id'] = $session_id;
            }else{
                $where['uid'] = $user_model['id'];
                $data['uid'] = $user_model['id'];
            }
            $model = self::where($where)->findOrEmpty();
            if($num<0){
                if(($model['num']+$num)<=0) {
                    $vo['c_num'] = 1;
                    $change_num = 1;
                }
            }
            try{
                $model->setAttrs($data);
                $model->setAttr('num',isset($vo['c_num'])?$change_num:\think\facade\Db::raw('num + ('.$num.')'));
                $model->save();
            }catch (\Exception $e){

            }

        }
    }

    //删除
    public static function cartDel(UserModel $user_model=null,array $input_data = [])
    {
        $session_id = $input_data['session_id']??'';
        $id = empty($input_data['id']) ? [] : ( !is_array($input_data['id']) ? [$input_data['id']] : $input_data['id'] );
        if(empty($id)) throw new \Exception('参数异常:id');
        $where = [];
        if(!empty($user_model)){
            $where[] = ['uid','=',$user_model['id']];
        }elseif(!empty($session_id)){
            $where[] = ['session_id','=',$session_id];
        }else{
            return;
        }
        self::where($where)->whereIn('id',$id)->select()->each(function($item){
            $item->delete();
        });

    }
    //修改信息
    public static function selfModInfo(UserModel $user_model=null,array $input_data = [])
    {
        $session_id = $input_data['session_id']??'';
        $mode = $input_data['mode']??'cart';
        $where = [];
        if(!empty($user_model)){
            $where[] = ['uid','=',$user_model['id']];
        }elseif(!empty($session_id)){
            $where[] = ['session_id','=',$session_id];
        }else{
            return;
        }
        if($mode=='cart'){
            $id = $input_data['id']??0;
            if(empty($id)) throw new \Exception(lang('err_data_param',['id'=>'id']));
            $where[] = ['id',is_array($id)?'in':'=',$id];
        }
//        dump($where);exit;
        $update_data =[];
        if(isset($input_data['is_checked'])){
            $update_data['is_checked'] = $input_data['is_checked']==1?1:0;
        }
        if(isset($input_data['num'])){
            $num = intval($input_data['num']);
            $update_data['num'] = $num <=0 ? 1 : $num;
        }

        count($update_data)>0 && self::where($where)->update($update_data);
    }


    //心愿单选中/取消
    public static function cartCheck($uid,$cid=null)
    {
        $where[] = ['uid','=',$uid];
//        self::where($where)->update(['is_checked'=>0]);
        if($cid){            
            $where[] = ['id','in',$cid];

//            if(!self::where($where)->count()) throw new \Exception('异常操作');
//            $bol = self::where($where)->update(['is_checked'=>1]);
        }
        self::where($where)->update(['is_checked'=>\think\facade\Db::raw('if(is_checked>0,0,1)')]);

        return true;
    }


    //清理购物车
    public static function clearAll(UserModel $user_model,array $input_data = [])
    {
        $where = [];
        $where[] = ['uid','=',$user_model['id']];
        $mch_id = $input_data['mch_id']??0; //按商户删除
        $cart_id = $input_data['cid']??0; //购物车id
        $is_force = $input_data['is_force']??0; //强制删除所有
        if(!empty($mch_id)){
            $where[] = ['mch_id','=',$mch_id];
        }elseif (!empty($cart_id)){
            $where[] = ['id','=',$cart_id];
        } elseif (!empty($is_force)){

        }

        return self::where($where)->delete();
    }




    /**
     * 获取所有数据
     * @param $input_data array
     * @throws
     * @return array
     * */
    public static function getAllData(array $input_data = [])
    {
        $session_id = $input_data['session_id']??0;
        $user_id = $input_data['uid']??0;
        if(empty($user_id) && empty($session_id)){
            return [];
        }
//        $user_model = UserModel::find($user_id);
//        if(empty($user_model)){
//            return [];
//        }
        //数据池
        $input_data['show_all'] = 1; //全部查询
        //获取购物车
        $where =[];
        if(!empty($user_id)){
            $where[] = ['uid','=',$user_id];
        }else{
            $where[] = ['session_id','=',$session_id];
        }

        $channel = $input_data['channel']??'';
        if($channel == 'cart'){
            $where[] = ['is_checked','=',1];
        }
//            dump($map_where);
        $cart_goods_ids = [];
        $cart_list = UserCartModel::where($where)->select()->each(function($item)use(&$pool_list,&$cart_goods_ids){
            !in_array($item['gid'],$cart_goods_ids) && $cart_goods_ids[] = $item['gid'];
        });

        if(empty($cart_goods_ids)){
            return [];
        }
        //查询产品信息
//        GoodsModel::$user_model = $user_model;
//        GoodsSkuPriceModel::$user_model = $user_model;
        $goods_pool = [];
        GoodsModel::getPageData(['limit'=>10000,'id'=>$cart_goods_ids])->each(function($item)use(&$goods_pool){
            $goods_pool[$item['id']] = $item;
        });

        //创建集合
        $collection = [];
        $cart_list->each(function($item,$index)use($goods_pool,&$collection){
            $goods_info = $goods_pool[$item['gid']]??null;
            if(!empty($goods_info)){
                $goods_info = clone $goods_info;


                $sku_id = $item['sku_id']??0;
                $g_key = $goods_info['id'].'_'.$sku_id;
                $goods_info->sku_id = $sku_id;
                $goods_info['buy_num'] = $item['num']??1;
                $goods_info['is_checked'] = $item['is_checked']??1;
                $goods_info['cart_id'] = $item['id']??0;
                $collection[$g_key] = clone $goods_info;
            }
        });

        if(!isset($input_data['handle'])){ //判断是否转义
            return $collection;
        }else{

            $goods_list = [];
            foreach ($collection as $key=>$goods){
                $goods_list[] = $goods->apiNormalInfo();
            }

            return $goods_list;
        }

    }


    /**
     * 获取按商家显示所有数据
     * @param $input_data array
     * @throws
     * @return array
     * */
    public static function getMchAllData(array $input_data = [])
    {
        $user_id = $input_data['uid']??0;
        if(empty($user_id)){
            return [];
        }
        $user_model = UserModel::find($user_id);
        if(empty($user_model)){
            return [];
        }
        //数据池
        $pool_list = [];
        $input_data['show_all'] = 1; //全部查询
        //获取购物车
        $where =[];
        $where[] = ['uid','=',$user_id];

        if(isset($input_data['mch_id'])){
            $where[] = ['mch_id','=',$input_data['mch_id']];
        }
        $channel = $input_data['channel']??'';
        if($channel == 'cart'){
            $where[] = ['is_checked','=',1];
        }
//            dump($map_where);
        $cart_goods_ids = [];
        $cart_list = UserCartModel::where($where)->select()->each(function($item)use(&$pool_list,&$cart_goods_ids){
            !in_array($item['gid'],$cart_goods_ids) && $cart_goods_ids[] = $item['gid'];
        });

        if(empty($cart_goods_ids)){
            return [];
        }
        //查询产品信息
        GoodsModel::$user_model = $user_model;
        GoodsSkuPriceModel::$user_model = $user_model;
        $goods_pool = [];
        GoodsModel::getPageData(['limit'=>10000,'id'=>$cart_goods_ids])->each(function($item)use(&$goods_pool){
            $goods_pool[$item['id']] = $item;
        });

        //创建集合
        $collection = [];
        $cart_list->each(function($item,$index)use($goods_pool,&$collection){
            $goods_info = $goods_pool[$item['gid']]??null;
            if(!empty($goods_info)){
                $goods_info = clone $goods_info;
                $merchant = $goods_info->getRelation('linkMerchant');
                $mch_id = $merchant['id']??0;
                $key = 'mch_'.$mch_id;
                if(!array_key_exists($key,$collection)){
                    $collection[$key] = [
                        'mch_info' => $merchant,
                        'goods_list'=>[],
                    ];
                }

                $sku_id = $item['sku_id']??0;
                $g_key = $goods_info['id'].'_'.$sku_id;
                $goods_info->sku_id = $sku_id;
                $goods_info['buy_num'] = $item['num']??1;
                $goods_info['is_checked'] = $item['is_checked']??1;
                $goods_info['cart_id'] = $item['id']??0;
                $collection[$key]['goods_list'][$g_key] = clone $goods_info;
            }
        });

        if(!isset($input_data['handle'])){ //判断是否转义
            return $collection;
        }else{

            $list = [];
            foreach ($collection as $key=>$vo){
                $merchant_info = $vo['mch_info'] ;
                $all_goods = $vo['goods_list']??[];
                $goods_list = [];
                foreach ($all_goods as $goods){
                    $goods_list[] = $goods->apiNormalInfo();
                }
                $list[] = [
                    'pay_money'=>'0.00',
                    'dis_money'=>'0.00',
                    'goods_total_money'=>'0.00',
                    'mch_info'=>empty($merchant_info)?(object)[]:$merchant_info->apiNormalInfo(),
                    'goods_list' => $goods_list,
                ];
            }

            return $list;
        }


    }



    //购物信息
    public function apiNormalInfo()
    {
        $linkGoods = $this->getRelation('linkGoods');
        $sku_info = empty($linkGoods)?null:$linkGoods->getRelation('linkSkuPriceOne');
//        dump($this->toArray());exit;
        return [
            'id' => (string)$this->getAttr('id'),
            'goods_id' => (string)$this->getAttr('gid'),
            'mch_id' => (string)$this->getAttr('mch_id'),
            'num' => (Int)$this->getAttr('num'),
            'cover_img' => (string)$linkGoods['cover_img'],
            'goods_name' => (string)$linkGoods['name'],
            'sold_price' => (string)$linkGoods['sold_price'],
            'og_price' => (string)$linkGoods['og_price'],
            'sku_id' => (int)$sku_info['id'],
            'sku_group_name' => (string)$sku_info['name'],
            'is_checked' => (int)$this->getAttr('is_checked'),
        ];
    }


    public function linkGoods()
    {

        return  $this->belongsTo(GoodsModel::class,'gid');
    }

    public function linkMch()
    {
        return  $this->belongsTo(UserModel::class,'mch_id');
    }


    public function linkGoodsAttrPrice()
    {
        return  $this->belongsTo(GoodsSkuPriceModel::class,'sku_id');
    }

}